const Koa = require('koa')
const Router = require('@koa/router')
const bodyParser = require('koa-bodyparser')
const cors = require('@koa/cors')
const app = new Koa()
const router = new Router()

app.use(bodyParser())
// https://juejin.cn/post/6844903873400799240
app.use(cors({
  origin: 'http://127.0.0.1:3000',
  credentials: true,
}))

// https://github.com/koajs/router/blob/master/API.md
router.get('/', (ctx) => {
  ctx.cookies.set('uid', 12, { httpOnly: false })
  ctx.body = 'good work'
}).post('/user', ctx => {
  const req = ctx.request.body
  const uname = req.username
  const uid = ctx.cookies.get('uid')
  ctx.body = {
    data: {
      uname,
      uid,
    },
    message: 'success',
  }
})

app.use(router.routes()).use(router.allowedMethods())

app.listen(9000, () => {
  console.log('http://127.0.0.1:9000 start success')
})